package cn.netswap.jeegorilla.framework.security.handler;


import cn.netswap.jeegorilla.framework.security.consts.SecurityConstants;
import cn.netswap.jeegorilla.framework.security.exception.ValidateCodeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Component
public class GorillaAuthenticationFailureHandler implements AuthenticationFailureHandler {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.info("认证失败");
        response.setContentType("application/json; charset=utf-8");

        //验证码的错误
        Map<String,Object> successMap = new HashMap<String,Object>();
        if(exception instanceof ValidateCodeException){
            successMap.put("status", SecurityConstants.FAILURESTATUS);
            successMap.put("msg",exception.getMessage());
            response.getWriter().write(objectMapper.writeValueAsString(successMap));
            return;
        }

        successMap.put("status", SecurityConstants.FAILURESTATUS);
        successMap.put("msg",SecurityConstants.FAILURESTATUS_MSG);
        response.getWriter().write(objectMapper.writeValueAsString(successMap));


    }
}
